<template>
	<!-- 翻译加载中的提示 -->
	<div v-if="!translationsLoaded" class="loading-container">
		<div class="loading-content">
			<div class="loading-spinner"></div>
			<div class="loading-text">加载中...</div>
		</div>
	</div>
	
	<div v-else style="background-color: #fff;padding-left: 18px;" class="u-f">
		<div>
			<div class="top-l">
				<!-- && infoData.questionTypeList[currentIndex[0]].questionList[currentIndex[1]].type != 'imageCanvas' -->

				<!-- 自动选择 -->
				<template v-if="!showQuestionList">
					<div
						v-if="!showQuestionList && getCurrentItem() && getCurrentItem().type == 'autoSelect'">
						<p class="canvas-title">
							{{ getCurrentItem().title }}
						</p>
						<div class="u-f-ajc " style="margin-top: 100px;"  >
								<div style="width: 300px;" v-if="currentItem.image && currentItem.image[0]"> 
									<img :src="BaseUrl + currentItem.image[0]" />
								</div>
							<div style="margin-left: 100px;">
								<div class="opt" @click="selectOpt(index)" :class="{ itemSelected: item.isSelected }"
									v-for="(item, index) in getCurrentItem().options">
									{{ item.label }}
								</div>
							</div>
						</div>
					</div>
					<!-- 画布 -->
					<div v-else-if="getCurrentItem() && (getCurrentItem().type === 'imageCanvas' || getCurrentItem().type === 'imageLeftCanvas' || getCurrentItem().type === 'imageDefault')">
						<CanvasBord ref="canvasBordRef" :info="getCurrentItem()"></CanvasBord>
					</div>
					<!-- 计算器 -->
					<div v-else-if="getCurrentItem() && (getCurrentItem().type === 'calculator')">
						<NumberBord 
							:info="getCurrentItem()" 
							:disabled="getCurrentItem().isAnswered" 
							:savedAnswer="getCurrentItem().userAnswer || ''"
							@confirm="confirmNumber"
						></NumberBord>
					</div>
					<!-- 图片 -->
					<div v-else-if="getCurrentItem() && (getCurrentItem().type === 'image')">
							<div class="main-title" style="margin-top: 100px;margin-bottom: 60px;">
							<span class="" v-if="getCurrentItem()">
								{{ getCurrentItem().title }}
							</span>
							<span v-else>
								{{ infoData.questionTypeList[currentIndex[0]].questionType }}
							</span>
						</div>
						<img :src="BaseUrl + getCurrentItem().image[0]" />
					</div>
					<!-- 默认标题 -->
					<div class="u-f-ajc" style="width: 100%;height: 100%;" v-else-if="!showQuestionList">
						<div class="main-title">
							<span class="" v-if="getCurrentItem() && getCurrentItem().title">
								{{ getCurrentItem().title }}
							</span>
							<span v-else-if="currentIndex[1] === -1 && infoData.questionTypeList[currentIndex[0]] && infoData.questionTypeList[currentIndex[0]].questionType">
								{{ infoData.questionTypeList[currentIndex[0]].questionType }}
							</span>
							<span v-else-if="getCurrentItem() && getCurrentItem().title">
								{{ getCurrentItem().title }}
							</span>
							<span v-else>
								{{ t('game.questionNumber', { number: currentIndex[0] + 1 }) }}
							</span>
						</div>
					</div>


				</template>


				<!-- 问题列表 -->
				<Qus ref="questionListRef" :infoData="infoData" v-if="showQuestionList" :currentIndex="currentIndex"
					@selectRow="selectRow" />
				<div class="main-bottom-bar">
					<button class="main-btn" @click="firstRow">{{ t('game.firstItem') }}</button>
					<button class="main-btn" @click="prevRow">{{ t('game.previousItem') }}</button>
					<button class="main-btn" @click="nextRow">{{ t('game.nextItem') }}</button>
					<button class="main-btn" @click="lastRow">{{ t('game.lastItem') }}</button>
					<button class="main-btn" @click="showQuestionList = !showQuestionList">{{ t('game.questionList') }}</button>
				</div>
			</div>
			<!-- {{ infoData.questionTypeList[currentIndex[0]].questionList[currentIndex[1]] }} -->
			<!-- {{ currentIndex }} -->
			<div class="bottom-l">
				<div class="answer-block">
					<div class="answer-title">{{ t('game.optionalAnswers') }}
						<span v-if="currentItem&&(currentItem.type =='calculator' || currentItem.type =='autoSelect')">{{ t('game.systemAutoJudge') }}</span>
					</div>
					<table class="answer-table" v-if="getCurrentItem() && getCurrentItem().options">
						<tbody>
							<tr
								v-for="(item, idx) in getCurrentItem().options"
								:key="idx"
								:class="isMultiple ? { selected: selectedIdxArr.includes(idx) } : { selected: item.isSelected }"
								@click="toggleSelect(idx)">
								<td style="width: 40px; text-align: center;">
									<input  v-if="isMultiple" type="checkbox" :checked="selectedIdxArr.includes(idx)"
										@click.stop="toggleSelect(idx)" />
									<input v-else type="radio" :checked="item.isSelected" @click.stop="toggleSelect(idx)" />
								</td>
								<td style="width: auto; white-space: normal;">{{ item.label }}</td>
							</tr>
						</tbody>
					</table>

					<table class="answer-table" v-else-if="infoData.questionTypeList[currentIndex[0]].options">
						<tbody>
							<tr v-for="(item, idx) in infoData.questionTypeList[currentIndex[0]].options" :key="idx"
								:class="{ selected: item.isSelected }" @click="toggleSelect(idx)">
								<td style="width: 40px; text-align: center;">
									<input v-if="isMultiple" type="checkbox" :checked="selectedIdxArr.includes(idx)"
										@click.stop="toggleSelect(idx)" />
									<input v-else type="radio" :checked="infoData.questionTypeList[currentIndex[0]].options.isSelected" @click.stop="toggleSelect(idx)" />
								</td>
								<td style="width: auto; white-space: normal;">{{ item.label }}</td>
							</tr>
						</tbody>
					</table>
				</div>
				<div class="score-block" style="background-color: #f4f9f7 !important;">
					<div class="score-title">{{ t('game.scoringCriteria') }}</div>
					<div class="score-content">
						<span v-if="getCurrentItem()" v-html=" getCurrentItem().scoreDesc">
						</span>
						<span v-else-if="infoData.questionTypeList[currentIndex[0]]" v-html="infoData.questionTypeList[currentIndex[0]].scoreDesc "> 
						</span>
					</div>
				</div>
			</div>
		</div>
		<div class="right-panel">
			<div class="top-r">
				<div class="desc-block">
					<div class="panel-title">{{ t('game.scaleDescription') }}</div>
					<div class="desc-content" v-if="infoData.questionTypeList[currentIndex[0]].desc">
						{{ infoData.questionTypeList[currentIndex[0]].desc }}
					</div>
					<div class="desc-content" v-html="getCurrentItem().desc "
						v-else-if="getCurrentItem() && getCurrentItem().desc">
					</div>
					<div class="desc-content" v-else v-html="infoData.desc"
					</div>
					<!-- <div v-else-if="infoData.questionList[currentIndex[0]].questionList[currentIndex[1]].desc">{{infoData.questionList[currentIndex[0]].questionList[currentIndex[1]].desc  }}</div> -->
				</div>
			</div>
							<GameBottom ref="gameBottomRef" @recorded="onRecorded" @recording-cancelled="onRecordingCancelled" :current-item-audio-prop="getCurrentItem()?.audio" :current-item-prop="getCurrentItem()" />
		</div>
		<div class="u-f-ajsb" style="position: fixed;bottom: 20px;right: 20px;width: 22vw;display: flex;">
			<button class="panel-action-btn primary" @click="generateReport">{{ t('game.generateReport') }}</button>
			<button class="panel-action-btn u-f-ajc" @click="DialogRef?.open(t('game.exitAssessment'))">{{ t('game.exitAssessment') }}</button>
		</div>
		<Dialog ref="DialogRef">
			<div>
				<div style="color: #000;font-size: 22px;margin-top: 20px;">
					{{ t('game.confirmExit') }}
				</div>
				<div class="dialog-btn" style="margin-top: 70px;">
					<button class="dialog-confirm" @click="doExit">{{ t('game.confirm') }}</button>
					<button class="dialog-cancel" @click="DialogRef.close()">{{ t('game.cancel') }}</button>
				</div>
			</div>
		</Dialog>
	</div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import Dialog from '../../components/Dialog.vue'
import { BaseUrl } from '../../utils/request'
import info from './components/a.json'
import CanvasBord from './components/CanvasBord.vue'
import GameBottom from './components/GameBottom.vue'
import NumberBord from './components/NumberBord.vue'
import Qus from './components/Qus.vue'

// 翻译系统
const translationVersion = ref(0)
const translationsLoaded = ref(false)
let t = (key: any, params?: any) => {
	// 如果翻译还没加载完成，返回空字符串避免闪烁
	if (!translationsLoaded.value) {
		return ''
	}
	
	const keys = key.split('.')
	let current: any = translations.value
	for (const k of keys) {
		if (current && typeof current === 'object') {
			current = current[k]
		} else {
			return key
		}
	}
	if (typeof current === 'string' && params) {
		return current.replace(/\{(\w+)\}/g, (match: any, key: any) => params[key] || match)
	}
	return current || key
}

const translations = ref<any>({})

async function initTranslations() {
	try {
		const currentLang = localStorage.getItem('language') || 'zh-CN'
		console.log('Loading translations for language:', currentLang)
		let langModule
		if (currentLang === 'en-US') {
			langModule = await import('../../i18n/locales/en-US')
		} else {
			langModule = await import('../../i18n/locales/zh-CN')
		}
		translations.value = langModule.default
		translationsLoaded.value = true
		translationVersion.value++
		console.log('Translations loaded successfully:', translations.value.report?.canvasName)
	} catch (error) {
		console.error('Failed to load translations:', error)
		translationsLoaded.value = true // 即使加载失败也要设置为true，避免一直不显示
	}
}

const router = useRouter()
const currentIndex = ref([0, -1, -1])
const infoData: any = ref(info)
const DialogRef: any = ref(null)
const canvasBordRef: any = ref(null)
const questionList = ref([])
const questionListRef = ref()
const showQuestionList = ref(false)
const notFrist = ref(false)
const selectedIdx = ref(-1)
const selectedIdxArr = ref<number[]>([])
const currentItem: any = ref(null)
const tableData: any = {}
const gameBottomRef: any = ref(null)
const isMultiple = computed(() => {
	const currentItem = getCurrentItem()
	return currentItem && currentItem.optionsType === 'multiple'
})

async function generateReport() {

	let user = JSON.parse(localStorage.getItem('user') || '{}')
	let taskId: any = localStorage.getItem('taskId')
	if (!taskId) {
		taskId = {
			id: ''
		}
	} else {
		taskId = JSON.parse(taskId)
	}
	let resource = localStorage.getItem('resource')
	if (router.options.history.state.back == '/') {
		taskId.id=''
		taskId.executionNumber = ''
		resource = '1'
	 }
	window.request?.('/task/actionTask', {
		method: 'POST', body: {
			id: localStorage.getItem('scaleId'),
			taskId: taskId.id,
			executionNumber: taskId.executionNumber,
			patientId: user.id,
			resource:resource,
			action: 3,
			linkName: localStorage.getItem('gameName'),
			linkId: localStorage.getItem('scaleId'),
			type: 2
		}
	})
	// 停止播放录音
	if (window.__playTimer) {
		clearInterval(window.__playTimer)
		window.__playTimer = null
	}
	
	// 保存当前canvas数据（如果是canvas类型题目）
	const currentItem = getCurrentItem()
	if (currentItem && (currentItem.type === 'imageCanvas' || currentItem.type === 'imageLeftCanvas' || currentItem.type === 'imageDefault')) {
		if (canvasBordRef.value && typeof canvasBordRef.value.getCanvasData === 'function') {
			const canvasData = await canvasBordRef.value.getCanvasData()
			if (canvasData) {
				// 计算canvas编号
				const [typeIdx, itemIdx, subIdx] = currentIndex.value
				let canvasCount = calculateCanvasCount(typeIdx, itemIdx, subIdx)
				
				currentItem.canvas = canvasData
				const translatedCanvasName = t('report.canvasName', { number: canvasCount })
				console.log('Canvas translation - key: report.canvasName, number:', canvasCount, 'result:', translatedCanvasName)
				currentItem.canvasName = translatedCanvasName
			}
		}
	}
	
	// 确保所有canvas题目都有正确的canvasName
	let canvasCount = 0
	infoData.value.questionTypeList.forEach((type: any, typeIdx: number) => {
		if (type.questionList && type.questionList.length > 0) {
			type.questionList.forEach((item: any, itemIdx: number) => {
				// 检查二级题目
				if (item.type === 'imageCanvas' || item.type === 'imageLeftCanvas' || item.type === 'imageDefault') {
					canvasCount++
					if (item.canvas && !item.canvasName) {
						item.canvasName = t('report.canvasName', { number: canvasCount })
						console.log('Setting canvasName for item:', typeIdx, itemIdx, 'number:', canvasCount, 'result:', item.canvasName)
			}
		}
				
				// 检查三级子题
				if (item.questionList && item.questionList.length > 0) {
					item.questionList.forEach((subItem: any, subIdx: number) => {
						if (subItem.type === 'imageCanvas' || subItem.type === 'imageLeftCanvas' || subItem.type === 'imageDefault') {
							canvasCount++
							if (subItem.canvas && !subItem.canvasName) {
								subItem.canvasName = t('report.canvasName', { number: canvasCount })
								console.log('Setting canvasName for subItem:', typeIdx, itemIdx, subIdx, 'number:', canvasCount, 'result:', subItem.canvasName)
							}
						}
					})
				}
			})
		}
	})

	tableData.endTime = new Date().getTime()
	console.log('Generate Report - tableData.user:', tableData.user)
	console.log('Generate Report - tableData.user.age:', tableData.user?.age)
	console.log('Generate Report - tableData.user.anamnesisid:', tableData.user?.anamnesisid)
	infoData.value={...infoData.value,...tableData}
	console.log('Generate Report - infoData.value.user:', infoData.value.user)
	console.log('Generate Report - infoData.value.user.age:', infoData.value.user?.age)
	console.log('Generate Report - infoData.value.user.anamnesisid:', infoData.value.user?.anamnesisid)
	localStorage.setItem('infoData',JSON.stringify(infoData.value))
	router.push('/table')
}
//选中
function selectOpt(index: number) {
	console.log(index);
	const currentItem = getCurrentItem()
	if (!currentItem || !currentItem.options) return
	
	currentItem.options.forEach((item: any) => {
		item.isSelected = false
	})
	currentItem.options[index].isSelected = true
}

// 键盘计算器
function confirmNumber(value: any) {
	console.log(value);
	const currentItem = getCurrentItem()
	if (!currentItem || !currentItem.options) return
	
	// 保存用户的答案
	currentItem.userAnswer = value.value
	// 标记为已答题
	currentItem.isAnswered = true
	
	if (value.correct) {
		currentItem.options[0].isSelected = true
		currentItem.options[1].isSelected = false
	} else {
		currentItem.options[0].isSelected = false
		currentItem.options[1].isSelected = true
	}
}

function isSelected(idx: number) {
	return isMultiple.value ? selectedIdxArr.value.includes(idx) : selectedIdx.value === idx
}
function toggleSelect(idx: number) {

	const currentItem = getCurrentItem()

	//自动判断
	if (getCurrentItem() && (getCurrentItem().type === 'calculator')) { 
		return
	}
	if (!currentItem) return

	if (isMultiple.value) {
		const arr = selectedIdxArr.value
		const i = arr.indexOf(idx)
		
		// 更新selectedIdxArr数组
		if (i > -1) {
			arr.splice(i, 1)
		} else {
			arr.push(idx)
		}
		
		// 同步更新infoData中的isSelected状态
		if (currentItem.options && currentItem.options[idx]) {
			currentItem.options[idx].isSelected = arr.includes(idx)
		}
	} else {
		// 单选逻辑
		if (currentItem.options) {
			currentItem.options.forEach((item: any) => {
				item.isSelected = false
			})
			if (currentItem.options[idx]) {
				currentItem.options[idx].isSelected = true
			}
		} else if (infoData.value.questionTypeList[currentIndex.value[0]].options) {
			// 处理大题级别的选项（向后兼容）
			infoData.value.questionTypeList[currentIndex.value[0]].options.forEach((item: any) => {
				item.isSelected = false
			})
			infoData.value.questionTypeList[currentIndex.value[0]].options[idx].isSelected = true
		}
	}
}

const isEmpty = () => {
	if (!infoData.value.questionTypeList[currentIndex.value[0]].questionList.length) {
		return true
	} else {
		return false
	}
}
function firstRow() {
	//判断是不是只有一个大题
	if (notFrist.value && currentIndex.value[0] == 0 && currentIndex.value[1] == 0 && currentIndex.value[2] == 0) {
		window.messageRef?.show(t('game.alreadyFirst'), "error")
		return
	}
	if (currentIndex.value[0] == 0 && currentIndex.value[1] == -1 && currentIndex.value[2] == -1) {
		window.messageRef?.show(t('game.alreadyFirst'), "error")
	} else {
		showQuestionList.value = false
		currentIndex.value = [0, -1, -1]
	}
}

function prevRow() {
	const [typeIdx, itemIdx, subIdx] = currentIndex.value
	
	//判断是不是只有一个大题
	if (notFrist.value && typeIdx == 0 && itemIdx == 0 && subIdx == 0) {
		window.messageRef?.show(t('game.alreadyFirst'), "error")
		return
	}
	if (typeIdx == 0 && itemIdx == -1 && subIdx == -1 && notFrist.value) {
		window.messageRef?.show(t('game.alreadyFirst'), "error")
		return
	}
	showQuestionList.value = false

	// 如果当前在三级子题
	if (subIdx > -1) {
		if (subIdx > 0) {
			// 跳到前一个三级子题
			currentIndex.value = [typeIdx, itemIdx, subIdx - 1]
		} else {
			// 跳到二级题目
			currentIndex.value = [typeIdx, itemIdx, -1]
		}
		return
	}

	// 如果当前在二级题目
	if (itemIdx > -1) {
		const currentItem = infoData.value.questionTypeList[typeIdx].questionList[itemIdx]
		
		if (itemIdx > 0) {
			// 跳到前一个二级题目的最后一个三级子题（如果有的话）
			const prevItem = infoData.value.questionTypeList[typeIdx].questionList[itemIdx - 1]
			if (prevItem.questionList && prevItem.questionList.length > 0) {
				currentIndex.value = [typeIdx, itemIdx - 1, prevItem.questionList.length - 1]
			} else {
				currentIndex.value = [typeIdx, itemIdx - 1, -1]
			}
		} else {
			// 跳到一级大题
			currentIndex.value = [typeIdx, -1, -1]
		}
		return
	}

	// 如果当前在一级大题，跳到上一个大题的最后一项
	if (typeIdx > 0) {
		const prevType = infoData.value.questionTypeList[typeIdx - 1]
		if (prevType.questionList && prevType.questionList.length > 0) {
			const lastItem = prevType.questionList[prevType.questionList.length - 1]
			if (lastItem.questionList && lastItem.questionList.length > 0) {
				currentIndex.value = [typeIdx - 1, prevType.questionList.length - 1, lastItem.questionList.length - 1]
			} else {
				currentIndex.value = [typeIdx - 1, prevType.questionList.length - 1, -1]
			}
		} else {
			currentIndex.value = [typeIdx - 1, -1, -1]
		}
	}
}
function nextRow() {
	const typeList = infoData.value.questionTypeList
	const [typeIdx, itemIdx, subIdx] = currentIndex.value

	// 检查是否已经到最后一项
	if (isLastItem(typeIdx, itemIdx, subIdx)) {
		window.messageRef?.show(t('game.alreadyLast'), "error")
		return
	}

	showQuestionList.value = false

	// 如果当前在一级大题
	if (itemIdx === -1) {
		// 如果该大类有子项，跳到第一个子项
		if (typeList[typeIdx].questionList && typeList[typeIdx].questionList.length > 0) {
			// 先跳到第一个二级题目，不管它有没有三级子题
			currentIndex.value = [typeIdx, 0, -1]
		} else if (typeIdx < typeList.length - 1 || isEmpty()) {
			// 跳到下一个大类
			currentIndex.value = [typeIdx + 1, -1, -1]
		}
		return
	}

	// 如果当前在二级题目
	if (subIdx === -1) {
		const currentItem = typeList[typeIdx].questionList[itemIdx]
		
		// 如果当前二级题目有三级子题，跳到第一个三级子题
		if (currentItem.questionList && currentItem.questionList.length > 0) {
			currentIndex.value = [typeIdx, itemIdx, 0]
			return
		}
		
		// 否则跳到下一个二级题目或下一级
		if (itemIdx < typeList[typeIdx].questionList.length - 1) {
			// 先跳到下一个二级题目本身，不直接跳到三级子题
			currentIndex.value = [typeIdx, itemIdx + 1, -1]
		} else if (typeIdx < typeList.length - 1) {
			// 跳到下一个大类
			currentIndex.value = [typeIdx + 1, -1, -1]
		}
		return
	}

	// 如果当前在三级子题
	const currentItem = typeList[typeIdx].questionList[itemIdx]
	if (subIdx < currentItem.questionList.length - 1) {
		// 跳到下一个三级子题
		currentIndex.value = [typeIdx, itemIdx, subIdx + 1]
	} else {
		// 跳到下一个二级题目或下一级
		if (itemIdx < typeList[typeIdx].questionList.length - 1) {
			// 先跳到下一个二级题目本身，不直接跳到三级子题
			currentIndex.value = [typeIdx, itemIdx + 1, -1]
		} else if (typeIdx < typeList.length - 1) {
			// 跳到下一个大类
			currentIndex.value = [typeIdx + 1, -1, -1]
		}
	}
}
function lastRow() {
	const typeList = infoData.value.questionTypeList
	const lastTypeIdx = typeList.length - 1
	const lastType = typeList[lastTypeIdx]
	
	if (isLastItem(currentIndex.value[0], currentIndex.value[1], currentIndex.value[2])) {
		window.messageRef?.show(t('game.alreadyLast'), "error")
		return
	}
	showQuestionList.value = false

	if (lastType.questionList && lastType.questionList.length > 0) {
		const lastItem = lastType.questionList[lastType.questionList.length - 1]
		if (lastItem.questionList && lastItem.questionList.length > 0) {
			// 跳到最后一个三级子题
			currentIndex.value = [lastTypeIdx, lastType.questionList.length - 1, lastItem.questionList.length - 1]
		} else {
			// 跳到最后一个二级题目
			currentIndex.value = [lastTypeIdx, lastType.questionList.length - 1, -1]
		}
	} else {
		currentIndex.value = [lastTypeIdx, -1, -1]
	}
}

// 辅助函数：检查是否是最后一项
function isLastItem(typeIdx: number, itemIdx: number, subIdx: number) {
	const typeList = infoData.value.questionTypeList
	const lastTypeIdx = typeList.length - 1
	
	if (typeIdx < lastTypeIdx) return false
	if (typeIdx > lastTypeIdx) return true
	
	// 在最后一个大题中
	const lastType = typeList[lastTypeIdx]
	if (!lastType.questionList || lastType.questionList.length === 0) {
		return itemIdx >= -1 && subIdx >= -1
	}
	
	const lastItemIdx = lastType.questionList.length - 1
	if (itemIdx < lastItemIdx) return false
	if (itemIdx > lastItemIdx) return true
	
	// 在最后一个二级题目中
	if (itemIdx === -1) return false // 还在大题级别，不是最后一项
	
	const lastItem = lastType.questionList[lastItemIdx]
	if (!lastItem.questionList || lastItem.questionList.length === 0) {
		return subIdx >= -1
	}
	
	const lastSubIdx = lastItem.questionList.length - 1
	return subIdx >= lastSubIdx
}

function doExit() {
	let user = JSON.parse(localStorage.getItem('user') || '{}')
	let taskId: any = localStorage.getItem('taskId')
	if (!taskId) {
		taskId = {
			id: ''
		}
	} else {
		taskId = JSON.parse(taskId)
	}
	let resource = localStorage.getItem('resource')
	if (router.options.history.state.back == '/') {
		taskId.id=''
		taskId.executionNumber = ''
		resource = '1'
	 }
	window.request?.('/task/actionTask', {
		method: 'POST', body: {
			id: localStorage.getItem('scaleId'),
			taskId: taskId.id,
			executionNumber: taskId.executionNumber,
			patientId: user.id,
			resource:resource,
			action: 4,
			linkName: localStorage.getItem('gameName'),
			linkId: localStorage.getItem('scaleId'),
			type: 2
		}
	})
	router.back()
}
function selectRow(idx: any, itemIdx: any, subIdx: any) {
	console.log(idx, itemIdx, subIdx)
	currentIndex.value = [idx, itemIdx, subIdx || -1]
	console.log(currentIndex.value)
	showQuestionList.value = false
}
onMounted(async () => {
	// 初始化翻译
	await initTranslations()
	
	//生成报告数据
	tableData.startTime = new Date().getTime();
	// 解析用户数据，确保是对象而不是字符串
	const userStr = localStorage.getItem('user')
	tableData.user = userStr ? JSON.parse(userStr) : null
	console.log('Game Index - userStr:', userStr)
	console.log('Game Index - parsed user:', tableData.user)
	console.log('Game Index - user age:', tableData.user?.age)
	console.log('Game Index - user anamnesisid:', tableData.user?.anamnesisid)
	tableData.gameName = localStorage.getItem('gameName')

	const scaleConfig: any = localStorage.getItem('scaleConfig')
	let temp = JSON.parse(scaleConfig)

	temp.questionTypeList.forEach((item: any, index: number) => {
		console.log(item);
		if ((temp.questionTypeList[index].questionList[0] && !temp.questionTypeList[index].questionList[0].title)) {
			temp.questionTypeList[index] = { ...temp.questionTypeList[index], ...temp.questionTypeList[index].questionList[0] }
			temp.questionTypeList[index].questionList = []

		}
	})
	//只有一个主题目
	if (!temp.questionTypeList[0].questionType) {
		notFrist.value = true
		currentIndex.value = [0, 0, -1]
		currentItem.value = infoData.value.questionTypeList[0].questionList[0]

	} else {
		currentItem.value = infoData.value.questionTypeList[0].questionList[-1]

	}
	if (scaleConfig) {
		infoData.value = temp
	}
	console.log(infoData.value);

})

// 监听currentIndex变化
watch(currentIndex, async (newValue, oldValue) => {
	// 保存canvas数据
	const [oldTypeIdx, oldItemIdx, oldSubIdx] = oldValue
	const oldItem = getItemByIndex(oldTypeIdx, oldItemIdx, oldSubIdx)
	
	if (oldItem && (oldItem.type === 'imageCanvas' || oldItem.type === 'imageLeftCanvas' || oldItem.type === 'imageDefault')) {
		if (canvasBordRef.value && typeof canvasBordRef.value.getCanvasData === 'function') {
			const canvasData = await canvasBordRef.value.getCanvasData()
			if (canvasData) {
				// 计算canvas编号
				let canvasCount = calculateCanvasCount(oldTypeIdx, oldItemIdx, oldSubIdx)
				oldItem.canvas = canvasData
				const translatedCanvasName = t('report.canvasName', { number: canvasCount })
				console.log('Canvas translation (old) - key: report.canvasName, number:', canvasCount, 'result:', translatedCanvasName)
				oldItem.canvasName = translatedCanvasName
			}
		}
	}
	
	// 处理录音状态
	if (gameBottomRef.value) {
		// 使用新的获取录音状态的方法
		const isCurrentlyRecording = typeof gameBottomRef.value.getIsRecording === 'function' 
			? gameBottomRef.value.getIsRecording() 
			: gameBottomRef.value.isRecording?.value
		
		console.log('Index.vue - 检查录音状态:', isCurrentlyRecording)
		// 如果正在录音，直接取消录音，不保存
		if (isCurrentlyRecording) {
			console.log('Index.vue - 正在录音中切换题目，取消录音不保存')
			// 取消录音，不保存任何数据
			if (typeof gameBottomRef.value.cancelRecordingSilently === 'function') {
				console.log('Index.vue - 调用 cancelRecordingSilently')
				gameBottomRef.value.cancelRecordingSilently()
				console.log('Index.vue - cancelRecordingSilently 调用完成')
			} else {
				console.error('Index.vue - cancelRecordingSilently 函数不存在')
			}
		} else {
			console.log('Index.vue - 没有正在进行的录音')
		}
	} else {
		console.log('Index.vue - gameBottomRef 不存在')
	}
	
	// 初始化倒计时和计时器
	if (gameBottomRef.value && typeof gameBottomRef.value.resetTimers === 'function') {
		gameBottomRef.value.resetTimers()
	}

	console.log('currentIndex changed:', { oldValue, newValue })
	currentItem.value = getCurrentItem()

	// 初始化多选状态
	if (isMultiple.value) {
		selectedIdxArr.value = []
		const currentItemData = getCurrentItem()
		if (currentItemData && currentItemData.options) {
			currentItemData.options.forEach((option: any, idx: number) => {
				if (option.isSelected) {
					selectedIdxArr.value.push(idx)
				}
			})
		}
	}

	// 如果新题目是canvas类型，处理画布显示
	const newItem = getCurrentItem()
	if (newItem && (newItem.type === 'imageCanvas' || newItem.type === 'imageLeftCanvas' || newItem.type === 'imageDefault')) {
		// 延迟处理画布，确保组件已经渲染
		setTimeout(() => {
			if (canvasBordRef.value) {
				// 如果有保存的画布数据，回显；否则清空
				if (newItem.canvas) {
					if (typeof canvasBordRef.value.loadCanvasData === 'function') {
						canvasBordRef.value.loadCanvasData(newItem.canvas)
					}
				} else {
					if (typeof canvasBordRef.value.clearCanvas === 'function') {
						canvasBordRef.value.clearCanvas()
					}
				}
			}
		}, 1)
	}
}, { deep: true })

function onRecorded(audio: string) {
	const currentItem = getCurrentItem()
	if (currentItem && audio) {
		currentItem.audio = audio
		// 同时保存录音时长
		if (gameBottomRef.value && typeof gameBottomRef.value.recordSec === 'function') {
			currentItem.recordDuration = gameBottomRef.value.recordSec()
			console.log('Index.vue - onRecorded 保存录音到题目:', currentItem.title || currentItem.questionType)
			console.log('Index.vue - 录音URL:', audio)
			console.log('Index.vue - 录音时长:', currentItem.recordDuration)
		}
	}
}

function onRecordingCancelled(audio: string) {
	console.log('Index.vue - onRecordingCancelled:', audio)
	const currentItem = getCurrentItem()
	console.log('Index.vue - currentIndex.value:', currentIndex.value)
	console.log('Index.vue - getCurrentItem():', currentItem)
	if (currentItem) {
		console.log('Index.vue - 当前题目:', currentItem.title || currentItem.questionType)
		console.log('Index.vue - 恢复录音到题目:', audio)
		console.log('Index.vue - 题目原有录音:', currentItem.audio)
		currentItem.audio = audio // 恢复之前的录音或设为空
		console.log('Index.vue - 题目录音已更新为:', currentItem.audio)
		
		// 强制更新，确保GameBottom组件收到新的props
		setTimeout(() => {
			console.log('Index.vue - 延迟检查，getCurrentItem()?.audio:', getCurrentItem()?.audio)
		}, 100)
	} else {
		console.error('Index.vue - 无法获取当前题目，无法保存录音')
	}
}



// 获取当前项目的函数
const getCurrentItem = () => {
	const [typeIdx, itemIdx, subIdx] = currentIndex.value
	try {

	 if (typeIdx < 0 || !infoData.value.questionTypeList[typeIdx])  	 return null
	} catch (error) {
		return null
		
	}
	
	const type = infoData.value.questionTypeList[typeIdx]
	
	// 如果是大题级别
	if (itemIdx === -1) {
		return type
	}
	
	if (itemIdx < 0 || !type.questionList || !type.questionList[itemIdx]) return null
	
	const item = type.questionList[itemIdx]
	
	// 如果是二级题目级别
	if (subIdx === -1) {
		return item
	}
	
	// 如果是三级子题级别
	if (subIdx < 0 || !item.questionList || !item.questionList[subIdx]) return null
	
	return item.questionList[subIdx]
}

// 辅助函数：根据索引获取项目
const getItemByIndex = (typeIdx: number, itemIdx: number, subIdx: number) => {
	if (typeIdx < 0 || !infoData.value.questionTypeList[typeIdx]) return null
	
	const type = infoData.value.questionTypeList[typeIdx]
	
	if (itemIdx === -1) return type
	if (itemIdx < 0 || !type.questionList || !type.questionList[itemIdx]) return null
	
	const item = type.questionList[itemIdx]
	
	if (subIdx === -1) return item
	if (subIdx < 0 || !item.questionList || !item.questionList[subIdx]) return null
	
	return item.questionList[subIdx]
}

// 辅助函数：计算canvas编号
const calculateCanvasCount = (typeIdx: number, itemIdx: number, subIdx: number) => {
	let canvasCount = 0
	
	for (let i = 0; i <= typeIdx; i++) {
		const typeList = infoData.value.questionTypeList[i]
		if (!typeList || !typeList.questionList) continue
		
		for (let j = 0; j < typeList.questionList.length; j++) {
			const item = typeList.questionList[j]
			
			// 检查二级题目
			if (item.type === 'imageCanvas' || item.type === 'imageLeftCanvas' || item.type === 'imageDefault') {
				canvasCount++
				if (i === typeIdx && j === itemIdx && subIdx === -1) {
					return canvasCount
				}
			}
			
			// 检查三级子题
			if (item.questionList && item.questionList.length > 0) {
				for (let k = 0; k < item.questionList.length; k++) {
					const subItem = item.questionList[k]
					if (subItem.type === 'imageCanvas' || subItem.type === 'imageLeftCanvas' || subItem.type === 'imageDefault') {
						canvasCount++
						if (i === typeIdx && j === itemIdx && k === subIdx) {
							return canvasCount
						}
					}
				}
			}
		}
		if (i === typeIdx) break
	}
	
	return canvasCount
}

</script>

<style scoped>
.itemSelected {
	background-color: #3bd76a !important;
}

.opt {
	text-align: left;
	padding-left: 30px;
	background-color: #96f3af;
	width: 400px;
	line-height: 40px;
	color: #333;
	font-weight: 500;
	border-radius: 20px;
	height: 40px;
	margin-bottom: 7px;
}

.dialog-btn {
	display: flex;
	justify-content: center;
	gap: 24px;
	margin-top: 32px;
}

.dialog-confirm {
	min-width: 90px;
	background: var(--theme-primary);
	color: #fff;
	border: none;
	border-radius: 8px;
	font-size: 18px;
	padding: 8px 0;
	cursor: pointer;
	transition: background 0.2s;
}

.dialog-confirm:hover {
	background: var(--theme-primary-hover);
}

.dialog-cancel {
	min-width: 90px;
	background: #f3f3f3;
	color: #888;
	border: none;
	border-radius: 8px;
	font-size: 18px;
	padding: 8px 0;
	cursor: pointer;
	transition: background 0.2s;
}

.dialog-cancel:hover {
	background: #e0e0e0;
}

.icon-row {
	width: 130px;
}

.jishi {
	color: #9e9fa0;
	font-size: 15px;
}

.u-f {
	display: flex;
	flex-direction: row;
}

.right-panel {
	display: flex;
	width: 22vw;
	margin-left: 18px;
	flex-direction: column;
	align-items: center;
}

.top-r {
	width: 100%;
	height: calc(30vh - 20px);
	background: #fff;
	border-radius: 12px;
	box-shadow: 0 2px 8px #f0f3fa;
	display: flex;
	flex-direction: column;
	overflow: hidden;
}

.top-l {
	position: relative;
	border-radius: 12px;
	width: 75vw;
	height: 68vh;
	display: flex;
	flex-direction: column;
	align-items: center;
	/* justify-content: center; */
	background-image: url('../../assets/image/wenbg.png') ;
	background-size: cover;
	background-position: center;
	background-repeat: no-repeat;
	
}

.main-title {
	font-size: 36px;
	font-weight: bold;
	color: #222;
	text-align: center;
	margin-bottom: 180px;
}

.main-bottom-bar {
	position: absolute;
	bottom: 18px;
	display: flex;
	justify-content: center;
	gap: 32px;
	margin-top: 180px;
}

.main-btn {
	min-width: 120px;
	height: 44px;
	border-radius: 22px;
	font-size: 18px;
	font-weight: 500;
	border: 1px solid #d3d3d5;
	outline: none;
	cursor: pointer;
	color: #000;
	background: #fefefe;
	box-shadow: 0 2px 8px rgba(21, 138, 192, 0.18);
	transition: background 0.2s, color 0.2s, box-shadow 0.2s;
}

.main-btn:hover {
	background: #f3f3f3;
	color: #666;
	box-shadow: 0 4px 16px rgba(21, 138, 192, 0.28);
}

.bottom-l {
	display: flex;
	gap: 10px;
	margin-top: 18px;
	height: calc(29vh - 20px);
	width: 75vw;
	overflow: hidden;
}

.answer-block,
.score-block {
	width: 80%;
	background: #f3f7fa;
	border-radius: 12px;
	box-shadow: 0 2px 8px #f0f3fa;
	padding: 0 0 18px 0;
	min-height: 120px;
	display: flex;
	flex-direction: column;
}

.answer-title,
.score-title {
	background: var(--theme-primary);
	color: #fff;
	font-size: 18px;
	font-weight: bold;
	border-radius: 12px 12px 0 0;
	padding: 8px 0 8px 18px;
}

.answer-options {
	display: flex;
	flex-direction: column;
	gap: 6px;
	padding: 12px 18px 0 18px;
}

.answer-option {
	display: flex;
	align-items: center;
	font-size: 15px;
	color: #444;
	gap: 8px;
	padding: 6px 0;
}

.score-content {
	flex: 1;
	background: #f3f7fa;
	border-radius: 0 0 12px 12px;
	min-height: 80px;
	overflow-y: auto;
	padding: 12px 18px;
	word-break: break-all;
	text-align: left;
}

.score-content::-webkit-scrollbar {
	width: 5px;
	background: transparent;
}

.score-content::-webkit-scrollbar-thumb {
	background: var(--theme-primary);
	border-radius: 3px;
}

.score-content::-webkit-scrollbar-track {
	background: transparent;
}

.control-panel {
	width: 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.panel-title {
	background: var(--theme-primary);
	color: #fff;
	font-size: 23px;
	font-weight: bold;
	border-radius: 16px 16px 0 0;
	padding: 5px 0;
	text-align: center;
	width: 100%;
	letter-spacing: 2px;
}

.panel-section {
	border-radius: 12px;
	margin: 0px 0 0 0;
	padding: 20px 18px 20px 18px;
	width: 92%;
	display: flex;
	flex-direction: column;
	align-items: center;
	border-bottom: #fff solid 1px;
}

.panel-row {
	display: flex;
	align-items: center;
	gap: 12px;
	width: 100%;
	justify-content: flex-start;
}

.panel-icon {
	margin-bottom: 8px;
	font-size: 32px;
	color: var(--theme-primary);
	width: 38px;
	text-align: center;
	background-color: #fff;
	border-radius: 50%;
	width: 70px;
	height: 70px;
}

.panel-time {
	font-size: 15px;
	background: #fff;
	border-radius: 22px;
	padding: 3px 30px;
	margin: 0 8px;
	border: 1px solid #e0e0e0;
	min-width: 160px;
	text-align: center;
	margin-bottom: 10px;
	letter-spacing: 0.4em;
	width: 70%;
	color: #333;
	font-size: 15px;

}

.panel-time2 {
	font-size: 15px;
	background: #fff;
	border-radius: 22px;
	padding: 3px 30px;
	margin: 0 8px;
	border: 1px solid #e0e0e0;
	min-width: 160px;
	text-align: center;
	margin-bottom: 10px;
	width: 70%;
}

.panel-btn {
	background: #fefefe;
	color: #333;
	border: none;
	border-radius: 8px;
	padding: 6px 18px;
	font-size: 15px;
	cursor: pointer;
	min-width: 100px;
	transition: background 0.2s, color 0.2s;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.panel-btn.primary {
	background: var(--theme-primary);
	color: #fff;
}

.panel-btn:disabled {
	background: #e0e0e0;
	color: #bbb;
	cursor: not-allowed;
}

.panel-label {
	color: #888;
	font-size: 15px;
	margin-top: 8px;
	text-align: left;
	width: 100%;
	padding-left: 38px;
}

.counter-row {
	gap: 24px;
}

.counter-group {
	display: flex;
	align-items: center;
	gap: 6px;
	width: 220px;
	margin-bottom: 8px !important;
	border-radius: 8px;
	padding: 4px 10px;
	margin: 0 6px;
}

.counter-label {
	color: #333;
	font-size: 15px;
	margin-right: 3px;

}

.counter-btn {
	background: #fff;
	color: #888;
	border: none;
	border-radius: 6px;
	padding: 2px 10px;
	font-size: 18px;
	cursor: pointer;
	transition: background 0.2s, color 0.2s;
}

.counter-value {
	font-size: 18px;
	color: #222;
	background-color: #fff;
	border-radius: 16px;
	margin: 0 6px;

	width: 80px;
	min-width: 24px;
	text-align: center;
	display: inline-block;
}

.panel-actions {
	display: flex;
	justify-content: center;
	gap: 24px;
	margin-top: 24px;
	width: 100%;
}

.panel-action-btn {
	min-width: 10.5vw;
	height: 44px;
	border-radius: 22px;
	font-size: 18px;
	font-weight: 500;
	border: 3px solid #d3d3d5;
	outline: none;
	cursor: pointer;
	color: var(--theme-primary);
	background: #fff;
	transition: background 0.2s, color 0.2s;
}

.panel-action-btn.primary {
	background: var(--theme-primary);
	color: #fff;
	border: none;
}

.panel-action-btn:hover {
	background: #eaf4fa;
}

.desc-block {
	display: flex;
	flex-direction: column;
	height: 100%;
}

.desc-content {
	flex: 1;
	padding: 18px 18px 12px 18px;
	color: #555;
	font-size: 16px;
	line-height: 1.8;
	background: #fff;
	border-radius: 0 0 12px 12px;
	overflow-y: auto;
	word-break: break-all;
	scrollbar-width: none;
	/* Firefox */
	-ms-overflow-style: none;
	/* IE 10+ */
}

.desc-content::-webkit-scrollbar {
	display: none;
}

.alarm-input {
	width: 40px;
	text-align: center;
	border: none;
	background: transparent;
	font-size: 15px;
	/* margin: 0 8px; */
}

.answer-block {
	background: #f3f7fa;
	border-radius: 12px;
	box-shadow: 0 4px 16px rgba(21, 138, 192, 0.08);
	padding: 0 0 10px 0;


	margin: 0 auto;
	overflow: hidden;
}

.answer-title {
	background: var(--theme-primary);
	color: #fff;
	font-weight: bold;
	font-size: 20px;
	border-radius: 12px 12px 0 0;
	padding: 6px 0;
	text-align: center;
	position: sticky;
	top: 0;
	z-index: 2;
}

.answer-table {
	width: 100%;
	border-collapse: separate;
	border-spacing: 0;
	display: block;
}

.answer-table tbody {
	display: block;
	max-height: calc(29vh - 70px);
	overflow-y: auto;
	width: 100%;
}

.answer-table tr {
	display: table;
	width: 100%;
	table-layout: fixed;
	transition: background 0.2s;
	cursor: pointer;
}

.answer-table tr:nth-child(even) {
	background: #f6f8fa;
}

.answer-table tr.selected {
	background: #f7de8e !important;
}

.answer-table td {
	text-align: left;
	padding: 10px 0px;
	font-size: 16px;
	vertical-align: middle;
	word-break: break-all;
	border-bottom: 1.5px solid #fff;
}

.answer-table tr:last-child td {
	border-bottom: none;
}

input[type='radio'] {
	accent-color: var(--theme-primary);
}

.answer-table tbody::-webkit-scrollbar {
	width: 5px;
	background: transparent;
}

.answer-table tbody::-webkit-scrollbar-thumb {
	background: var(--theme-primary);
	border-radius: 3px;
}

.answer-table tbody::-webkit-scrollbar-track {
	background: transparent;
}

.canvas-title {
	width: 70vw;
	padding: 10px 0;
	text-align: center;
	font-size: 30px;
	margin: 20px auto 5px auto;
	background-color: rgba(0, 0, 0, 0.2);
}

.setting-bg {
	width: 100vw;
	height: 100vh;
	background: var(--theme-primary);
	display: flex;
	align-items: center;
	justify-content: center;
	overflow: hidden;
}

.loading-container {
	width: 100vw;
	height: 100vh;
	background: #fff;
	display: flex;
	align-items: center;
	justify-content: center;
}

.loading-content {
	text-align: center;
}

.loading-spinner {
	width: 50px;
	height: 50px;
	border: 4px solid #f3f3f3;
	border-top: 4px solid var(--theme-primary);
	border-radius: 50%;
	animation: spin 1s linear infinite;
	margin: 0 auto 20px auto;
}

.loading-text {
	font-size: 18px;
	color: #666;
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}
</style>